<script setup lang="ts">
import { ref, reactive, watch, onMounted, defineProps } from "vue";
import ReCol from "@/components/ReCol";
import { formRules } from "./utils/rule";
import { message } from "@/utils/message";
import { formProps, type FormInstance } from "element-plus";
import AddCoordinate from "@/components/AddCoordinate/index.vue";
import { useMapStoreHook } from "@/store/modules/map";
import { GetAllStation } from '@/utils/api/dispatch/station'
import { PureTableBar } from "@/components/RePureTableBar";
import { useCrossDept } from "./utils/crossHook";
import { getCross } from '@/utils/api/dispatch/cross'
import { taskareaList, taskareaAdd, taskareaUpdate, taskareaDel, getTaskarea } from '@/utils/api/dispatch/jobRegion'
import { GetAllAgv } from '@/utils/api/dispatch/agv'
import { cloneDeep } from "lodash";
import Konva from "konva";
import { useDept } from "./utils/hook";
import { ElMessageBox } from 'element-plus'
import { wareList } from '@/utils/api/BasicManagement/warehouse'
import { GetStorePlaceList, GetAllStorePlaceList } from '@/utils/api/BasicManagement/locations'
import { useTranslationLang } from "@/layout/hooks/useTranslationLang";
const { locale } = useTranslationLang();
import { useI18n } from "vue-i18n";
const { t } = useI18n();

const warehouseList = ref([]);
const getWareList = () => {
    wareList().then(({ Content: { Results } }) => {
        warehouseList.value = Results
    })
}

const pureMap = useMapStoreHook()

interface Props {
    formInline?: any,
    isUpdate?: boolean
}

const props = withDefaults(defineProps<Props>(), {
    isUpdate: false
});

const ruleFormRef = ref();
const newFormInline: { [key: string]: any; } = ref({
    name: "",
    status: 1,
    stationList: [{}],
    agvNameList: [],
    priority: 1,
    note: "",
    type: 1,
    transfer: '',
    lane: null,
    warehouseid: null,
    floor: null,
    locstate: null,
    tasknum: null
});
const formCargo = ref()
const isUpdate = ref(props.isUpdate);
const agvOptions = ref([]);
const {
    columns,
    loading,
    dataList,
    onSearch,
    pagination,
} = useCrossDept();

function getRef() {
    return ruleFormRef.value;
}

function crossNameChange(val) {
    pureMap.$patch((state) => {
        state.crossDetail.name = val
    })
}

function chores(title, data) {
    message(`${title}成功`, {
        type: "success"
    });
    pureMap.targetCross.name(`job-${pureMap.crossDetail.name}`)
    // pureMap.targetCross.attrs.type = 1
    onSearch()
    pureMap.$patch({
        crossSwitch: false
    })
    isUpdate.value = false
    resetForm(ruleFormRef.value)
}

/**
 * 新增
*/
const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            var data = newFormInline.value
            if (data.type === 1) {
                data.transfer = data.transfer.toString()
            } else {
                data.transfer = ''
            }
            if (data.type === 2) {
                //将data里的floor字段转换为数字类型
                data.floor = Number(data.floor)
                data.tasknum = Number(data.tasknum)
            } else {
                data.floor = 0
                data.tasknum = 0
                data.warehouseid = 0
            }
            if (data.type === 3 || data.type === 5) {
                data.agvids = null
                data.agvNameList = null
            } else {
                data.agvNameList = []
                newFormInline.value?.agvids?.forEach(v => {
                    data.agvNameList.push(agvOptions.value.find(item => item.AgvId === v)?.AgvName)
                })
                data.agvids = newFormInline.value?.agvids?.toString()
            }
            //如果不是number类型就提示
            if (isNaN(data.floor)) {
                message('请输入正确的楼层', {
                    type: "error"
                });
                newFormInline.value.floor = null
                return
            }
            if (isUpdate.value) {
                taskareaUpdate(data).then(res => {
                    if (res.Code === 0) chores('修改', data)
                    // pureMap.targetCross.children.forEach(v=>{
                    //   if(v.name() === 'circle'){
                    //     v.fill('red')
                    //   }else{
                    //     v.stroke('red')
                    //   }
                    // })
                })
            } else {
                taskareaAdd(data).then(res => {
                    if (res.Code === 0) {
                        chores('新增', data)
                    }
                })
            }
        } else {
            console.log('error submit!', fields)
        }
    })
}

// 重置
const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
    connect()
    isUpdate.value = false

    if (isUpdate.value) {
        pureMap.targetCross.destroy()

        pureMap.targetCross.children.forEach(v => {
            if (v.name() === 'circle') {
                v.fill('red')
            } else {
                v.stroke('red')
            }
        })
    }
}

// 编辑
async function crossUpdate(id: number) {
    let { Content } = await getTaskarea(id)
    // console.log('编辑=>', Content);

    newFormInline.value = Content
    newFormInline.value.agvids = newFormInline.value?.agvids?.split(',').map(v => { return Number(v) })
    newFormInline.value.transfer = newFormInline.value?.transfer?.split(',')
    for (let key in pureMap.crossDetail) {
        pureMap.$patch((state) => {
            state.crossDetail[key] = Content[key]
        })
    }
    isUpdate.value = true

    pureMap.getCross(pureMap.stageKonva.find(`.job-${pureMap.crossDetail.name}`)[0])
}

// 删除区域
function deleteCross(formEl) {
    if (!formEl) return
    formEl.validate((valid, fields) => {
        if (valid) {
            var data = newFormInline.value
            data.stationids = newFormInline.value?.stationids?.toString()
            if (isUpdate.value) {
                ElMessageBox.confirm(
                    `是否确认删除名称为${data.name}的数据项?`,
                    '提示',
                    {
                        confirmButtonText: '确认',
                        cancelButtonText: '取消',
                        type: 'warning',
                        center: true
                    }
                ).then(() => {
                    taskareaDel(data.id).then(res => {
                        if (res.Code === 0) {
                            pureMap.stageKonva.find(`.job-${data.name}`)[0].destroy()
                            chores('删除', data)
                        }
                    })
                }).catch(() => { })
            }
        } else {
            console.log('error submit!', fields)
        }
    })
}

// 关联form与pureMap
function connect() {
    Object.keys(pureMap.crossDetail).forEach(v => {
        pureMap.$patch((state) => {
            state.crossDetail[v] = newFormInline.value[v]
        })
    })
}

onMounted(async () => {
    // 站点下拉
    const { Content } = await GetAllAgv()
    agvOptions.value = Content

    // 中转工位
    let { Content: from } = await GetAllStorePlaceList({ status: 0 })
    formCargo.value = from

    connect()

    getWareList()
})


defineExpose({ getRef, crossUpdate, resetForm });
</script>

<template>
    <el-form ref="ruleFormRef" :model="newFormInline" :rules="formRules" label-width="50px"
        :label-position="locale === 'en' ? 'top' : 'right'">
        <el-row :gutter="30">
            <re-col :value="12" :xs="24" :sm="24">
                <el-form-item :label="t('jobRegion.name')" prop="name">
                    <el-input v-model="newFormInline.name" size="small" clearable @change="crossNameChange" />
                </el-form-item>
            </re-col>
            <re-col :value="12" :xs="24" :sm="24">
                <el-form-item :label="t('jobRegion.status')" prop="status">
                    <el-select v-model="newFormInline.status" size="small" style="width:100%">
                        <el-option :label="t('jobRegion.enable')" :value="1" />
                        <el-option :label="t('jobRegion.disable')" :value="0" />
                        <el-option :label="t('jobRegion.lock')" :value="2" />
                    </el-select>
                </el-form-item>
            </re-col>
            <re-col :value="24" :xs="24" :sm="24">
                <el-form-item :label="t('jobRegion.type')" prop="type">
                    <el-select v-model="newFormInline.type" size="small" style="width:100%">
                        <el-option :label="t('jobRegion.taskArea')" :value=1 />
                        <el-option :label="t('jobRegion.floor')" :value=2 />
                        <el-option :label="t('jobRegion.rotatingCargoArea')" :value=3 />
                        <el-option :label="t('jobRegion.noRotationAreaWithoutLoad')" :value=4 />
                        <el-option :label="t('jobRegion.turnAroundArea')" :value=5 />
                        <el-option :label="t('jobRegion.chargingArea')" :value=6 />
                        <el-option :label="t('jobRegion.prohibitedAccessArea')" :value=7 />
                    </el-select>
                </el-form-item>
            </re-col>
            <re-col :value="24" :xs="24" :sm="24"
                v-if="newFormInline.type === 1 || newFormInline.type === 2 || newFormInline.type === 7">
                <el-form-item
                    :label="newFormInline.type === 7 ? t('jobRegion.prohibitedVehicles') : t('jobRegion.vehicle')"
                    prop="agvids" :label-width="newFormInline.type === 7 ? '78px' : '50px'">
                    <el-select v-model="newFormInline.agvids" size="small" multiple style="width:100%">
                        <el-option v-for="item in agvOptions" :key="item.AgvId" :label="item.AgvName"
                            :value="item.AgvId" />
                    </el-select>
                </el-form-item>
            </re-col>
            <re-col :value="24" :xs="24" :sm="24" v-if="newFormInline.type === 1 || newFormInline.type === 2">
                <el-form-item :label="t('jobRegion.rules')" prop="priority">
                    <el-select v-model="newFormInline.priority" size="small" style="width:100%">
                        <el-option :label="t('jobRegion.randomDistribution')" :value="1" />
                        <el-option :label="t('jobRegion.vehicleSequenceDistribution')" :value="2" />
                    </el-select>
                </el-form-item>
            </re-col>
            <re-col :value="24" :xs="24" :sm="24" v-if="newFormInline.type === 2">
                <el-form-item :label="t('jobRegion.warehouse')" prop="warehouseid">
                    <el-select v-model="newFormInline.warehouseid" size="small" style="width:100%">
                        <el-option v-for="item in warehouseList" :key="item.id" :label="item.name" :value="item.id" />
                    </el-select>
                </el-form-item>
            </re-col>
            <re-col :value="24" :xs="24" :sm="24" v-if="newFormInline.type === 2">
                <el-form-item :label="t('jobRegion.floor')" prop="floor">
                    <el-input v-model="newFormInline.floor" size="small" clearable />
                </el-form-item>
            </re-col>
            <re-col :value="24" :xs="24" :sm="24" v-if="newFormInline.type === 2">
                <el-form-item :label="t('jobRegion.numberOfSecondedTasks')" prop="tasknum" label-width="105px">
                    <el-input v-model="newFormInline.tasknum" size="small" clearable />
                </el-form-item>
            </re-col>
            <re-col :value="24" :xs="24" :sm="24" v-if="newFormInline.type === 1">
                <el-form-item :label="t('jobRegion.transitCargoLocation')" prop="transfer" label-width="76px">
                    <el-select v-model="newFormInline.transfer" filterable clearable style="width:100%" multiple
                        size="small">
                        <el-option v-for="item in formCargo" :key="item.Id" :label="item.Code" :value="item.Code" />
                    </el-select>
                </el-form-item>
            </re-col>
            <re-col :value="24" :xs="24" :sm="24" v-if="newFormInline.type === 1">
                <el-form-item :label="t('jobRegion.lane')" prop="lane" label-width="76px">
                    <el-input v-model="newFormInline.lane" size="small" clearable />
                </el-form-item>
            </re-col>
            <re-col :value="24" :xs="24" :sm="24" v-if="newFormInline.type !== 7">
                <el-form-item :label="t('jobRegion.locationAllocationLogic')" prop="locstate" label-width="103px">
                    <el-select v-model="newFormInline.locstate" size="small" style="width:100%">
                        <el-option :label="t('jobRegion.none')" :value="0" />
                        <el-option :label="t('jobRegion.automaticAllocationManualClearing')" :value="1" />
                        <el-option :label="t('jobRegion.rotatingAllocation')" :value="2" />
                    </el-select>
                </el-form-item>
            </re-col>
            <re-col :value="24" :xs="24" :sm="24">
                <el-form-item :label="t('jobRegion.region')" prop="stationList" style="font-weight: 700;">
                    <Add-coordinate :data="newFormInline.stationList"></Add-coordinate>
                </el-form-item>
            </re-col>
            <re-col :value="24" :xs="24" :sm="24">
                <el-form-item :label="t('jobRegion.remarks')" prop="note">
                    <el-input v-model="newFormInline.note" size="small" clearable type="textarea" />
                </el-form-item>
            </re-col>
            <re-col :value="24" :xs="24" :sm="24">
                <el-form-item>
                    <el-button type="primary" @click="submitForm(ruleFormRef)">{{ t('jobRegion.submit') }}</el-button>
                    <el-button type="danger" @click="resetForm(ruleFormRef)">{{ t('jobRegion.clearData') }}</el-button>
                    <el-button type="danger" @click="deleteCross(ruleFormRef)" v-show="isUpdate">{{
                        t('cross.delete') }}</el-button>
                </el-form-item>
            </re-col>
        </el-row>
    </el-form>

    <!-- <PureTableBar title="交管列表" :columns="columns" size="small" @refresh="onSearch">
      <template v-slot="{ size, dynamicColumns }">
        <pure-table ref="tableRef" adaptive align-whole="center" row-key="Id" showOverflowTooltip table-layout="auto"
          :loading="loading" :size="size" :data="dataList" :columns="dynamicColumns" :pagination="pagination"
          :paginationSmall="size === 'small' ? true : false" :header-cell-style="{
            background: 'var(--el-fill-color-light)',
            color: 'var(--el-text-color-primary)'
          }">
          <template #operation="{ row }">
            <el-button class="reset-margin" :size="size" link type="primary" @click="crossUpdate(row.id)">
              编辑
            </el-button>
          </template>
</pure-table>
</template>
</PureTableBar> -->
</template>

<style lang="scss" scoped>
.el-radio {
    margin-right: 16px;
}
</style>
